package com.yimi.appstore.download;

import java.util.HashMap;
import java.util.Iterator;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.view.View;
import android.widget.RemoteViews;

import com.yimi.appstore.R;
import com.yimi.appstore.activity.MainActivity;
import com.yimi.appstore.download.DownloadManager.OnTaskChangeListener;
import com.yimi.appstore.util.Util;

public class DownloadNotifier extends Service {
	public static final String TAG = "DownloadNotifier";
	private int APP_ID = 888;
	private int MUSIC_ID = 999;
	private NotificationManager mNotificationManager;
	private DownloadManager mdDownloadManager;
	private HashMap<Integer, DownloadTask> mDownloadingSoftware = new HashMap<Integer, DownloadTask>();
	private HashMap<Integer, DownloadTask> mDownloadingMusic = new HashMap<Integer, DownloadTask>();
	private int appFinishCount, musicFinishCount;
	private RemoteViews appRemoteViews, musicRemoteViews;
	private Notification app, music;
	private boolean inited = false;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		mdDownloadManager = DownloadManager
				.getInstance(getApplicationContext());
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		mdDownloadManager.addOnTaskChangeListener(TAG,
				new OnTaskChangeListener() {
					@Override
					public void onTaskStateUpdate(int state,
							DownloadTask downloadTask) {
						DownloadEntry de = downloadTask.getDownloadEntry();
						if (de.getMimeType() == 1) {
							switch (state) {
							case DownloadTask.STATE_DOWNLOADING:
								mDownloadingSoftware.put(de.getId(),
										downloadTask);
								break;
							case DownloadTask.STATE_FINISH:
								appFinishCount++;
							case DownloadTask.STATE_DELETE:
							case DownloadTask.STATE_DELETE_WITH_FILE:
							case DownloadTask.STATE_STOP:
								mDownloadingSoftware.remove(de.getId());
							}
						} else if (de.getMimeType() == 2) {
							switch (state) {
							case DownloadTask.STATE_DOWNLOADING:
								mDownloadingMusic.put(de.getId(), downloadTask);
								break;
							case DownloadTask.STATE_FINISH:
								musicFinishCount++;
							case DownloadTask.STATE_DELETE:
							case DownloadTask.STATE_DELETE_WITH_FILE:
							case DownloadTask.STATE_STOP:
								mDownloadingMusic.remove(de.getId());
							}
						}
						init();
						refreshAll();
					}

					@Override
					public void onTaskProgressUpdate(DownloadTask downloadTask) {
						if (inited)
							refreshAll();
					}
				});
		return super.onStartCommand(intent, flags, startId);
	}

	private void init() {
		inited = false;
		mNotificationManager.cancel(APP_ID);
		mNotificationManager.cancel(MUSIC_ID);
		if (mDownloadingSoftware.isEmpty())
			app = new Notification(R.drawable.ic_launcher, appFinishCount
					+ "个应用下载完成", System.currentTimeMillis());
		else
			app = new Notification(R.drawable.ic_launcher,
					mDownloadingSoftware.size() + "个应用正在下载",
					System.currentTimeMillis());
		appRemoteViews = new RemoteViews("com.yimi.appstore", R.layout.notifier);
		Intent intent = new Intent(DownloadNotifier.this,
				MainActivity.class);
//		intent.putExtra("id", ManagementPageActivity.TO_SOFTWARE_DOWNLOAD);
		PendingIntent pendingIntent = PendingIntent.getActivity(
				getApplicationContext(), APP_ID, intent, 0);
		app.contentIntent = pendingIntent;
		if (mDownloadingMusic.isEmpty())
			music = new Notification(R.drawable.ic_launcher, musicFinishCount
					+ "首音乐下载完成", System.currentTimeMillis());
		else
			music = new Notification(R.drawable.ic_launcher,
					mDownloadingMusic.size() + "首音乐正在下载",
					System.currentTimeMillis());

		Intent intent1 = new Intent(DownloadNotifier.this,
				MainActivity.class);
//		intent1.putExtra("id", ManagementPageActivity.TO_MUSIC_DOWNLOAD);
		PendingIntent pendingIntent1 = PendingIntent.getActivity(
				getApplicationContext(), MUSIC_ID, intent1, 0);
		musicRemoteViews = new RemoteViews("com.zxm.app", R.layout.notifier);
		music.contentIntent = pendingIntent1;
		inited = true;
	}

	private void refreshAll() {
		if (!mDownloadingSoftware.isEmpty()) {
			Iterator<DownloadTask> i = mDownloadingSoftware.values().iterator();
			StringBuffer appList = new StringBuffer(mDownloadingSoftware.size()
					+ "个应用:");
			int appCurrentBytes = 0;
			int appTotalBytes = 0;
			while (i.hasNext()) {
				DownloadTask dt = i.next();
				DownloadEntry de = dt.getDownloadEntry();
				appList.append(de.getFileName() + ",");
				appCurrentBytes += de.getCurrentBytes();
				appTotalBytes += de.getTotalBytes();
			}
			appList.deleteCharAt(appList.length() - 1);
			appRemoteViews.setTextViewText(R.id.notifier_count, "应用下载");
			appRemoteViews.setTextViewText(R.id.notifier_names,
					appList.toString());
			appRemoteViews.setTextViewText(
					R.id.notifier_tip,
					"已下载:" + Util.convertStorage((long) appCurrentBytes)
							+ "/"
							+ Util.convertStorage((long) appTotalBytes));
			appRemoteViews.setViewVisibility(R.id.notifier_progress,
					View.VISIBLE);
			appRemoteViews.setProgressBar(R.id.notifier_progress,
					appTotalBytes, appCurrentBytes, false);
			app.contentView = appRemoteViews;
			app.flags = Notification.FLAG_ONGOING_EVENT;
			mNotificationManager.notify(APP_ID, app);
		} else if (appFinishCount != 0) {
			appRemoteViews.setTextViewText(R.id.notifier_count, "精推");
			appRemoteViews.setTextViewText(R.id.notifier_names, "");
			appRemoteViews.setViewVisibility(R.id.notifier_progress, View.GONE);
			appRemoteViews.setTextViewText(R.id.notifier_tip, appFinishCount
					+ "个应用下载完成，点击查看");
			app.contentView = appRemoteViews;
			app.flags = Notification.FLAG_AUTO_CANCEL;
			mNotificationManager.notify(APP_ID, app);
		} else
			mNotificationManager.cancel(APP_ID);
		// music
		if (!mDownloadingMusic.isEmpty()) {
			Iterator<DownloadTask> i = mDownloadingMusic.values().iterator();
			StringBuffer musicList = new StringBuffer(mDownloadingMusic.size()
					+ "首音乐:");
			int musicCurrentBytes = 0;
			int musicTotalBytes = 0;
			while (i.hasNext()) {
				DownloadTask dt = i.next();
				DownloadEntry de = dt.getDownloadEntry();
				musicList.append(de.getFileName() + ",");
				musicCurrentBytes += de.getCurrentBytes();
				musicTotalBytes += de.getTotalBytes();
			}
			musicList.deleteCharAt(musicList.length() - 1);
			musicRemoteViews.setTextViewText(R.id.notifier_count, "音乐下载");
			musicRemoteViews.setTextViewText(R.id.notifier_names,
					musicList.toString());
			musicRemoteViews.setViewVisibility(R.id.notifier_progress,
					View.VISIBLE);
			musicRemoteViews.setTextViewText(R.id.notifier_tip, "已下载:"
					+ Util.convertStorage((long) musicCurrentBytes)
					+ "/" + Util.convertStorage((long) musicTotalBytes));
			musicRemoteViews.setProgressBar(R.id.notifier_progress,
					musicTotalBytes, musicCurrentBytes, false);
			music.contentView = musicRemoteViews;
			music.flags = Notification.FLAG_ONGOING_EVENT;
			mNotificationManager.notify(MUSIC_ID, music);
		} else if (musicFinishCount != 0) {
			musicRemoteViews.setTextViewText(R.id.notifier_count, "一米");
			musicRemoteViews.setTextViewText(R.id.notifier_names, "");
			musicRemoteViews.setViewVisibility(R.id.notifier_progress,
					View.GONE);
			musicRemoteViews.setTextViewText(R.id.notifier_tip,
					musicFinishCount + "首音乐下载完成，点击查看");
			music.contentView = musicRemoteViews;
			music.flags = Notification.FLAG_AUTO_CANCEL;
			mNotificationManager.notify(MUSIC_ID, music);
		} else
			mNotificationManager.cancel(MUSIC_ID);
	}
}